package com.sky.local_ads.networkmanager;

import java.io.Serializable;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sky.local_ads.listener.ResponseListener;

public class NetworkManager {
	
	public static <T extends Serializable> void executeJsonAsync(ServiceRequest request,final Class<T> entity,final ResponseListener<T> listener) throws Exception{
		try{
			AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
			switch (request.getVerb()) {
			case GET:
				asyncHttpClient.get(request.getURL(), new AsyncHttpResponseHandler(){
					@Override
					public void onSuccess(int arg0, Header[] arg1, String arg2) {
						super.onSuccess(arg0, arg1, arg2);
						listener.onSuccess(prepareResponse(arg2, entity));
					}
					
					@Override
					public void onFailure(Throwable arg0, String arg1) {
						super.onFailure(arg0, arg1);
						listener.onFailure(arg0, arg1);
					}
				});
				break;

			default:
				break;
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	private static <T> T prepareResponse(String responseString,Class<T> clazz) {

		T t = null;

		Gson gson = new Gson();
		t = gson.fromJson(responseString, clazz);
		return t;
	}

}
